#支付宝支付配制
#导入支付基类
from .pay import AliPay
import os
from loguru import logger

#初始化阿里支付对象
def get_ali_object():
    # 沙箱环境地址：https://openhome.alipay.com/platform/appDaily.htm?tab=info
    from utils.config import config
    
    app_id = config.ALIPAY_APP_ID  #  APPID （沙箱应用）

    # 支付完成后，支付偷偷向这里地址发送一个post请求，识别公网IP,如果是 192.168.20.13局域网IP ,支付宝找不到，def page2() 接收不到这个请求
    notify_url = config.ALIPAY_NOTIFY_URL

    # 支付完成后，跳转的地址。
    return_url = config.ALIPAY_RETURN_URL
    
    # 验证回调地址是否为公网可访问地址
    localhost_keywords = ['localhost', '127.0.0.1', '192.168.', '10.', '172.16.', '172.17.', '172.18.', '172.19.', '172.20.', '172.21.', '172.22.', '172.23.', '172.24.', '172.25.', '172.26.', '172.27.', '172.28.', '172.29.', '172.30.', '172.31.']
    placeholder_keywords = ['your-public-url', 'your-ngrok-url', 'yourdomain.com', 'example.com']
    
    notify_is_local = any(keyword in notify_url for keyword in localhost_keywords)
    return_is_local = any(keyword in return_url for keyword in localhost_keywords)
    notify_is_placeholder = any(keyword in notify_url for keyword in placeholder_keywords)
    return_is_placeholder = any(keyword in return_url for keyword in placeholder_keywords)
    
    if notify_is_local or return_is_local or notify_is_placeholder or return_is_placeholder:
        warning_msg = "\n" + "="*80 + "\n"
        warning_msg += "⚠️  警告：支付宝回调地址配置错误，可能导致 502 错误！\n"
        warning_msg += "="*80 + "\n"
        if notify_is_local:
            warning_msg += f"❌ notify_url 是本地地址: {notify_url}\n"
        if return_is_local:
            warning_msg += f"❌ return_url 是本地地址: {return_url}\n"
        if notify_is_placeholder:
            warning_msg += f"❌ notify_url 包含占位符: {notify_url}\n"
        if return_is_placeholder:
            warning_msg += f"❌ return_url 包含占位符: {return_url}\n"
        warning_msg += "\n解决方案：\n"
        warning_msg += "1. 运行配置修复脚本：\n"
        warning_msg += "   python fix_alipay_config.py\n"
        warning_msg += "2. 或手动在 .env 文件中设置正确的公网地址：\n"
        warning_msg += "   ALIPAY_NOTIFY_URL=https://your-ngrok-url.ngrok.io/api/payment/alipay/notify\n"
        warning_msg += "   ALIPAY_RETURN_URL=https://your-ngrok-url.ngrok.io/api/payment/alipay/return\n"
        warning_msg += "3. 确保 ngrok 正在运行：ngrok http 8000\n"
        warning_msg += "="*80 + "\n"
        logger.warning(warning_msg)

    # 获取项目根目录
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    merchant_private_key_path = os.path.join(base_dir, 'keys', 'private.txt')  # 应用私钥
    alipay_public_key_path = os.path.join(base_dir, 'keys', 'public.txt')  # 支付宝公钥

    alipay = AliPay(
        appid=app_id,
        app_notify_url=notify_url,
        return_url=return_url,
        app_private_key_path=merchant_private_key_path,
        alipay_public_key_path=alipay_public_key_path,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥
        debug=config.ALIPAY_DEBUG,  # 默认False,
    )
    return alipay

